﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;

namespace GRWL.BZSC.UI
{
    public partial class EditMaterialFrm : BaseFrm
    {

        /// <summary>
        ///新增时当前所在分类
        /// </summary>
        public SelectItem CurrentCategory { get; set; }

        /// <summary>
        /// 传入编码规则
        /// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        /// <summary>
        /// 临时变量
        /// </summary>
        public XMaterial XM { get; set; }
        /// <summary>
        /// 编辑模式时传入id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 库存Id
        /// </summary>
        public int StockId { get; set; }
        /// <summary>
        /// 是否编辑模式
        /// </summary>
        public bool EditMode { get; set; }

        Common.BillOperateType _OperateType = Common.BillOperateType.None;
        /// <summary>
        /// 操作状态
        /// </summary>
        Common.BillOperateType OperateType
        {
            get
            {
                return this._OperateType;
            }
            set
            {
                this._OperateType = value;
                initBtns();
            }
        }

        public EditMaterialFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();
        }

        private void EditMaterialFrm_Load(object sender, EventArgs e)
        {
            Common.BindOptionComboBox(this.cbBoxCheckMethod, GRWL.BZSC.Common.EnumCommon.OptionType.检验类型, this.BaseDataProxy, string.Empty);
            Common.BindOptionComboBox(this.cbBoxSource, GRWL.BZSC.Common.EnumCommon.OptionType.来源类型, this.BaseDataProxy, string.Empty);
            init();
        }

        /// <summary>
        /// 重设置按钮状态
        /// </summary>
        public void initBtns()
        {
            btnAdd.Enabled = (this.OperateType != Common.BillOperateType.Add) && (this.OperateType != Common.BillOperateType.Update);
            btnSave.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
            btnDelete.Enabled = (this.OperateType == Common.BillOperateType.Add) || (this.OperateType == Common.BillOperateType.Update);
        }

        private void init()
        {
            if (this.EditMode)//编辑模式数据绑定
            {
                this.txtBoxCode.ReadOnly = true;

                this.XM = this.BaseDataProxy.GetXMaterial(this.Id, this.StockId,null);
                if (this.XM != null)
                {
                    this.txtBoxName.Text = this.XM.Material.cnName;
                    this.txtBoxCode.Text = this.XM.Material.code;

                    if (this.XM.Material.badDepot != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.BadDepotName;
                        item.Key = this.XM.BadDepotCode;
                        item.Value = this.XM.Material.badDepot.ToString();
                        this.slcrBadDepot.SetSelected(item);
                    }

                    this.txtBoxBrand.Text = this.XM.Material.brand;

                    if (this.XM.Material.category != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.CategoryName;
                        item.Key = this.XM.CategoryCode;
                        item.Value = this.XM.Material.category.ToString();
                        this.slcrCategory.SetSelected(item);
                    }

                    //Common.BindOptionComboBox(this.cbBoxCheckMethod, GRWL.BZSC.Common.EnumCommon.OptionType.检验类型, this.BaseDataProxy, this.XM.Material.checkMethod);
                    this.cbBoxCheckMethod.SelectedItem = this.XM.Material.checkMethod;

                    this.cbBoxSource.SelectedItem = this.XM.Material.source;

                    if (this.XM.Material.department != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.DepartmentName;
                        item.Key = this.XM.DepartmentCode;
                        item.Value = this.XM.Material.department.ToString();
                        this.slcrDepartment.SetSelected(item);
                    }

                    if (this.XM.Material.depot != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.DepotName;
                        item.Key = this.XM.DepotCode;
                        item.Value = this.XM.Material.depot.ToString();
                        this.slcrDepot.SetSelected(item);
                    }

                    this.txtBoxEnName.Text = this.XM.Material.enName;

                    if (this.XM.Material.expire != null)
                        this.dateTimePicker1.Value = Convert.ToDateTime(this.XM.Material.expire);

                    this.chkBoxIsCheck.Checked = this.XM.Material.isCheck;
                    this.chkBoxIsPurchase.Checked = this.XM.Material.isPurchase;
                    this.chkBoxIsNominal.Checked = this.XM.Material.isNominal;

                    //产品项目
                    if (this.XM.Material.projectId != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.Material.projectCode;
                        item.Key = this.XM.Material.projectCode;
                        item.Value = this.XM.Material.projectId.ToString();
                        this.slcrProjectNo.SetSelected(item);
                    }

                    if (this.XM.Material.provider != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.TraderName;
                        item.Key = this.XM.TraderName;
                        item.Value = this.XM.Material.provider.ToString();
                        this.slcrTrader.SetSelected(item);
                    }

                    this.txtBoxPPrice.Text = this.XM.Material.purchasePrice.ToString();

                    this.txtBoxSPrice.Text = this.XM.Material.salePrice.ToString();

                    if (this.XM.Material.scrapDepot != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.ScrapDepotName;
                        item.Key = this.XM.ScrapDepotCode;
                        item.Value = this.XM.Material.scrapDepot.ToString();
                        this.slcrScrapDepot.SetSelected(item);
                    }

                    this.txtBoxSpecs.Text = this.XM.Material.specs;

                    if (!string.IsNullOrEmpty(this.XM.Material.unit))
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.Material.unit;
                        item.Key = this.XM.Material.unit;
                        item.Value = string.Empty;
                        this.slcrUnit.SetSelected(item);
                    }

                    this.chkBoxUnusable.Checked = this.XM.Material.unusable;

                    this.chkBoxUpdateNominal.Checked = this.XM.Material.updateNominal;

                    if (this.XM.Material.waitingDepot != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.WaitingDepotName;
                        item.Key = this.XM.WaitingDepotCode;
                        item.Value = this.XM.Material.waitingDepot.ToString();
                        this.slcrWaitingDepot.SetSelected(item);
                    }

                    //工序
                    if (this.XM.Material.workstage != null)
                    {
                        SelectItem item = new SelectItem();
                        item.Name = this.XM.WorkstageCode;
                        item.Key = this.XM.WorkstageName;
                        item.Value = this.XM.Material.workstage.ToString();
                        this.slcrWorkstage.SetSelected(item);
                    }
                }
            }
            else
            {
                if (this.codeRule != null)
                {
                    //this.txtBoxCode.Text = this.BaseDataProxy.GetSerialNo((int)GRWL.BZSC.Common.EnumCommon.CodeRuleType.Other, this.codeRule.header, this.codeRule.len,!string.IsNullOrEmpty(this.codeRule.header), this.codeRule.autoFill,false);
                    this.txtBoxCode.ReadOnly = this.codeRule.autoCode;
                }

                if (this.CurrentCategory != null)
                    this.slcrCategory.SetSelected(this.CurrentCategory);
            }
        }

        /// <summary>
        /// 重置窗体清除数据
        /// </summary>
        private void clearForm()
        {
            for (int i = 0; i < this.groupBox1.Controls.Count; i++)
            {
                if (this.groupBox1.Controls[i].Name.StartsWith("txtBox"))
                {
                    this.groupBox1.Controls[i].Text = string.Empty;
                    this.groupBox1.Controls[i].Tag = null;
                }
                else if (this.groupBox1.Controls[i].Name.StartsWith("slcr"))
                {
                    if (this.groupBox1.Controls[i].Name != "slcrCategory")//分类不重置
                    {
                        Selector slcr = this.groupBox1.Controls[i] as Selector;
                        slcr.SetSelected(null);
                    }
                }
                else if (this.groupBox1.Controls[i].Name.StartsWith("chkBox"))
                {
                    CheckBox ckb = this.groupBox1.Controls[i] as CheckBox;
                    ckb.Checked = false;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.EditMode && !this.codeRule.autoCode && this.txtBoxCode.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请输入物料编码！");
                this.txtBoxCode.Focus();
                return;
            }

            if (this.txtBoxName.Text.Trim() == string.Empty)
            {
                MessageBox.Show("请输入中文名称！");
                this.txtBoxName.Focus();
                return;
            }

            if (this.slcrUnit.SelectedValue() == null)
            {
                MessageBox.Show("请输入单位！");
                this.slcrUnit.Focus();
                return;
            }

            XMaterial xm = new XMaterial();
            xm.Material = new TB_Material();
            if (this.slcrBadDepot.SelectedValue() != null)
            {
                xm.Material.badDepot = Convert.ToInt32(this.slcrBadDepot.SelectedValue());
                xm.BadDepotCode = this.slcrBadDepot.CurrentSelectItem.Key;
                xm.BadDepotName = this.slcrBadDepot.CurrentSelectItem.Name;
            }
            xm.Material.brand = this.txtBoxBrand.Text.Trim();
            if (this.slcrCategory.SelectedValue() != null)
            {
                xm.Material.category = Convert.ToInt32(this.slcrCategory.SelectedValue());
                xm.CategoryCode = this.slcrCategory.CurrentSelectItem.Key;
                xm.CategoryName = this.slcrCategory.CurrentSelectItem.Name;
            }
            xm.Material.checkMethod = this.cbBoxCheckMethod.Text;
            xm.Material.cnName = this.txtBoxName.Text.Trim();
            if (this.slcrDepartment.SelectedValue() != null)
            {
                xm.Material.department = Convert.ToInt32(this.slcrDepartment.SelectedValue());
                xm.DepartmentCode = this.slcrDepartment.CurrentSelectItem.Key;
                xm.DepartmentName = this.slcrDepartment.CurrentSelectItem.Name;
            }
            if (this.slcrDepot.SelectedValue() != null)
            {
                xm.Material.depot = Convert.ToInt32(this.slcrDepot.SelectedValue());
                xm.DepotCode = this.slcrDepot.CurrentSelectItem.Key;
                xm.DepotName = this.slcrDepot.CurrentSelectItem.Name;
            }
            xm.Material.enName = this.txtBoxEnName.Text.Trim();
            xm.Material.expire = this.dateTimePicker1.Value;
            xm.Material.isCheck = this.chkBoxIsCheck.Checked;
            xm.Material.isPurchase = this.chkBoxIsPurchase.Checked;
            xm.Material.isNominal = this.chkBoxIsNominal.Checked;
            if (this.slcrProjectNo.SelectedValue() != null)
            {
                xm.Material.projectId = Convert.ToInt32(this.slcrProjectNo.SelectedValue());
                xm.Material.projectCode = this.slcrProjectNo.CurrentSelectItem.Key;
            }
            if (this.slcrTrader.SelectedValue() != null)
            {
                xm.Material.provider = Convert.ToInt32(this.slcrTrader.SelectedValue());
                xm.TraderName = this.slcrTrader.CurrentSelectItem.Name;
            }
            if (!string.IsNullOrEmpty(this.txtBoxPPrice.Text))
                xm.Material.purchasePrice = Convert.ToDecimal(this.txtBoxPPrice.Text.Trim());
            if (!string.IsNullOrEmpty(this.txtBoxSPrice.Text))
                xm.Material.salePrice = Convert.ToDecimal(this.txtBoxSPrice.Text.Trim());
            if (this.slcrScrapDepot.SelectedValue() != null)
            {
                xm.Material.scrapDepot = Convert.ToInt32(this.slcrScrapDepot.SelectedValue());
                xm.ScrapDepotCode = this.slcrScrapDepot.CurrentSelectItem.Key;
                xm.ScrapDepotName = this.slcrScrapDepot.CurrentSelectItem.Name;
            }
            xm.Material.source = this.cbBoxSource.Text;
            xm.Material.specs = this.txtBoxSpecs.Text.Trim();
            xm.Material.unit = this.slcrUnit.SelectedText();
            xm.Material.unusable = this.chkBoxUnusable.Checked;
            xm.Material.updateNominal = this.chkBoxUpdateNominal.Checked;
            //material.updateTime = DateTime.Now;
            if (this.slcrWaitingDepot.SelectedValue() != null)
            {
                xm.Material.waitingDepot = Convert.ToInt32(this.slcrWaitingDepot.SelectedValue());
                xm.WaitingDepotCode = this.slcrWaitingDepot.CurrentSelectItem.Key;
                xm.WaitingDepotName = this.slcrWaitingDepot.CurrentSelectItem.Name;
            }
            if (this.slcrWorkstage.SelectedValue() != null)
            {
                xm.Material.workstage = Convert.ToInt32(this.slcrWorkstage.SelectedValue());
                xm.WorkstageCode = this.slcrWorkstage.CurrentSelectItem.Key;
                xm.WorkstageName = this.slcrWorkstage.CurrentSelectItem.Name;
            }

            Common.OperateType opType = Common.OperateType.Add;
            bool ok = false;
            if (this.EditMode)
            {
                xm.Material.id = this.Id;
                xm.Material.code = this.txtBoxCode.Text.Trim();
                xm.Material.updateTime = DateTime.Now;
                ok = this.BaseDataProxy.UpdateMaterial(xm.Material);
                opType = Common.OperateType.Update;
            }
            else
            {
                xm.Material.code = this.BaseDataProxy.GetSerialNo((int)GRWL.BZSC.Common.EnumCommon.CodeRuleType.Other, this.codeRule.header, this.codeRule.len, !string.IsNullOrEmpty(this.codeRule.header), this.codeRule.autoFill, false);
                int newId = this.BaseDataProxy.AddMaterial(xm.Material);
                //if (newId > 0)
                //{
                //    xm.Material.id = newId;

                //    ok = this.BaseDataProxy.UpdateMaterial(xm.Material);
                //}
                ok = newId > 0;
                this.OperateType = Common.BillOperateType.None;
            }

            if (ok)
            {
                CommonEventArg<XMaterial> arg = new CommonEventArg<XMaterial>(xm, opType);
                GRWL.BZSC.Common.EventCommon.OnMaterialUdDGVEvnt(sender, arg);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void slcrCategory_SelectorClick(object sender, EventArgs e)
        {
            OptionFrm frm = new OptionFrm();
            frm.Text = "选择物料分类";
            frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.物料分类;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrCategory.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrUnit_SelectorClick(object sender, EventArgs e)
        {
            OptionFrm frm = new OptionFrm();
            frm.Text = "选择单位";
            frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.单位类型;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrUnit.SetSelected(frm.SelectorItem);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.EditMode = false;
            this.Id = 0;
            this.XM = null;
            this.StockId = 0;
            clearForm();
            this.txtBoxCode.Text = this.BaseDataProxy.GetSerialNo((int)GRWL.BZSC.Common.EnumCommon.CodeRuleType.Other, this.codeRule.header, this.codeRule.len, !string.IsNullOrEmpty(this.codeRule.header), this.codeRule.autoFill, false);
            this.txtBoxCode.ReadOnly = this.codeRule.autoCode;
            this.OperateType = Common.BillOperateType.Add;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (this.EditMode)
                {
                    //if (this.BaseDataProxy.DeleteMaterial(this.Id))
                    //{
                    //    CommonEventArg<XMaterial> arg = new CommonEventArg<XMaterial>(this.XM, Common.OperateType.Delete);
                    //    GRWL.BZSC.Common.EventCommon.OnMaterialUdDGVEvnt(sender, arg);
                    //    clearForm();
                    //    this.OperateType = Common.BillOperateType.None;
                    //}

                    SPResult spr = this.BaseDataProxy.SPDeleteMaterial(this.Id);
                    if (spr.Ok)
                    {
                        CommonEventArg<XMaterial> arg = new CommonEventArg<XMaterial>(this.XM, Common.OperateType.Delete);
                        GRWL.BZSC.Common.EventCommon.OnMaterialUdDGVEvnt(sender, arg);
                        clearForm();
                        this.OperateType = Common.BillOperateType.None;
                    }
                    else
                        MessageBox.Show("删除失败，" + spr.Msg);
                }
            }
        }

        private void slcrWorkstage_SelectorClick(object sender, EventArgs e)
        {
            OptionFrm frm = new OptionFrm();
            frm.IsWorkstage = true;
            frm.Text = "选择工序";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrWorkstage.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrDepartment_SelectorClick(object sender, EventArgs e)
        {
            DeptFrm frm = new DeptFrm();
            frm.Text = "选择部门";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrDepartment.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrTrader_SelectorClick(object sender, EventArgs e)
        {
            TraderFrm frm = new TraderFrm();
            frm.SearchSupplierMode();
            frm.Text = "选择主供应商";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrTrader.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrDepot_SelectorClick(object sender, EventArgs e)
        {
            DepotFrm frm = new DepotFrm();
            frm.SearchMode();
            frm.Text = "选择主仓库";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrDepot.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrWaitingDepot_SelectorClick(object sender, EventArgs e)
        {
            DepotFrm frm = new DepotFrm();
            frm.SearchMode();
            frm.Text = "选择待检仓";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrWaitingDepot.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrBadDepot_SelectorClick(object sender, EventArgs e)
        {
            DepotFrm frm = new DepotFrm();
            frm.SearchMode();
            frm.Text = "选择不良品仓";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrBadDepot.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrScrapDepot_SelectorClick(object sender, EventArgs e)
        {
            DepotFrm frm = new DepotFrm();
            frm.SearchMode();
            frm.Text = "选择报废仓";
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.slcrScrapDepot.SetSelected(frm.SelectorItem);
            }
        }

        private void slcrUnit_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Options[] datas = this.BaseDataProxy.FindOptions(GRWL.BZSC.Common.EnumCommon.OptionType.单位类型.ToString(), null, this.slcrUnit.GetComboBoxText());
            this.slcrUnit.ReBindComboBox<TB_Options>(datas, "id", "name", "code");
        }

        private void slcrCategory_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Options[] datas = this.BaseDataProxy.FindOptions(GRWL.BZSC.Common.EnumCommon.OptionType.物料分类.ToString(), null, this.slcrCategory.GetComboBoxText());
            this.slcrCategory.ReBindComboBox<TB_Options>(datas, "id", "name", "code");
        }

        private void slcrTrader_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Trader[] datas = this.BaseDataProxy.FindTraders(null, true, null, null, null, this.slcrTrader.GetComboBoxText());
            this.slcrTrader.ReBindComboBox<TB_Trader>(datas, "id", "name", "code");
        }

        private void slcrWorkstage_SelectorTextUpdate(object sender, EventArgs e)
        {
            //TB_Workstage[] datas = this.BaseDataProxy.FindWorkstage(null, true, null, null, null, this.slcrTrader.GetComboBoxText());
        }

        private void slcrDepartment_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Department[] datas = this.BaseDataProxy.FindDepartments(null, null, this.slcrDepartment.GetComboBoxText());
            this.slcrDepartment.ReBindComboBox<TB_Department>(datas, "id", "name", "code");
        }

        private void slcrBadDepot_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Depot[] datas = this.BaseDataProxy.FindDepots(null, this.slcrBadDepot.GetComboBoxText(), null);
            this.slcrBadDepot.ReBindComboBox<TB_Depot>(datas, "id", "name", "code");
        }

        private void slcrDepot_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Depot[] datas = this.BaseDataProxy.FindDepots(null, this.slcrDepot.GetComboBoxText(), null);
            this.slcrDepot.ReBindComboBox<TB_Depot>(datas, "id", "name", "code");
        }

        private void slcrWaitingDepot_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Depot[] datas = this.BaseDataProxy.FindDepots(null, this.slcrWaitingDepot.GetComboBoxText(), null);
            this.slcrWaitingDepot.ReBindComboBox<TB_Depot>(datas, "id", "name", "code");
        }

        private void slcrScrapDepot_SelectorTextUpdate(object sender, EventArgs e)
        {
            TB_Depot[] datas = this.BaseDataProxy.FindDepots(null, this.slcrScrapDepot.GetComboBoxText(), null);
            this.slcrScrapDepot.ReBindComboBox<TB_Depot>(datas, "id", "name", "code");
        }
    }
}
